/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkgUtil.pkgJavaDB;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Armando
 */
public class ShemaDB {

    public static void createShema(Connection dbConnection) throws SQLException {
        //Verifico primero si existe la tabla CONTEXTO
        DatabaseMetaData dbMetaData = dbConnection.getMetaData();
        ResultSet rs = null;
        try {
            rs = dbMetaData.getTables(null, null, ConstantsJavaDB.NAME_TABLA_CONTEXTO, null);
            if (rs == null) {
                crearTablas(dbConnection);
            } else {
                boolean poseeRegistros = false;
                while (rs.next()) {
                    poseeRegistros = true;
                    String nomTabla = rs.getString(3);
                    if (nomTabla != null && !nomTabla.equals(ConstantsJavaDB.NAME_TABLA_CONTEXTO)) {
                        crearTablas(dbConnection);
                        return;
                    }
                }
                if (!poseeRegistros) {
                    crearTablas(dbConnection);
                }
            }
        } finally {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        }

    }

    private static void crearTablas(Connection dbConnection) throws SQLException {
        Statement statement = null;
        try {
            statement = dbConnection.createStatement();
            statement.execute(ConstantsJavaDB.SCRIPT_CREATE_TABLE_CONTEXTO);
        } catch (SQLException ex) {
            throw new SQLException("Error en la creacion de tablas: " + ex.getMessage());
        } finally {
            if (statement != null && !statement.isClosed()) {
                statement.close();
            }
        }
    }
}
